package com.crm.system.controller.cluePoolManager;

import com.alibaba.fastjson.JSONObject;
import com.crm.common.model.DataResponse;
import com.crm.common.model.DhPageInfo;
import com.crm.common.model.DhResponse;
import com.crm.common.model.Enum.CluePoolNatureEnum;
import com.crm.common.model.Enum.ResponseCodeEnum;
import com.crm.common.util.CommonUtils;
import com.crm.model.entity.cluePoolManager.Clue;
import com.crm.model.qo.cluePoolManager.ClueAddQO;
import com.crm.model.qo.cluePoolManager.ClueExtentQO;
import com.crm.model.qo.cluePoolManager.ClueQO;
import com.crm.model.qo.cluePoolManager.ClueSeniorQO;
import com.crm.model.vo.cluePoolManager.*;
import com.crm.system.service.cluePoolManager.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author luojie
 * @date 2021/1/7 10:28
 */
@RestController
@RequestMapping("/clue")
@Slf4j
public class ClueController {

    @Autowired
    private ClueService clueService;

    @Autowired
    private ClueFollowService clueFollowService;

    @Autowired
    private ClueReceiveService clueReceiveService;

    @Autowired
    private ClueReturnService clueReturnService;

    @Autowired
    private ClueVisitRecordService clueVisitRecordService;

    @Autowired
    private ClueContactService clueContactService;

    /**
     * 添加线索
     * @param clueAddQO
     * @return
     */
    @PostMapping("/addClue")
    public DataResponse addClue(HttpServletRequest request,
                                          @RequestBody ClueAddQO clueAddQO) {
        try {
            int result = clueService.addClue(clueAddQO);
            if (result ==0) {
                return new DhResponse(ResponseCodeEnum.OK.getResponseCode());
            } else if(result ==2){
                return new DhResponse(ResponseCodeEnum.CLUE_NAME_DUPLICATE.getResponseCode());
            } else if(result ==3){
                return new DhResponse(ResponseCodeEnum.CLUE_QCC_CHECK.getResponseCode());
            } else{
                return new DhResponse(ResponseCodeEnum.POOL_CAPACITY_EXCEEDED.getResponseCode());
            }
        }catch(Exception e){
            log.error("clue addClue error:", e);
            return new DhResponse(ResponseCodeEnum.SERVICE_ERROR.getResponseCode());
        }
    }

    /**
     *(管理模块)线索公海--查看线索清单
     * @return
     */
    @PostMapping("/selectClueList")
    public DataResponse selectClueList(@RequestParam(value = "pageIndex", required = true) Integer pageIndex,//页码
                                       @RequestParam(value = "pageSize", required = true) Integer pageSize,//分页大小
                                       @RequestParam(value="sortName",required = false) String sortName,//排序列名字
                                       @RequestParam(value="sortOrder",required = false) String sortOrder,//排序规则(asc/desc)
                                       ClueQO clueQO,//普通查询条件
                                       ClueSeniorQO clueSeniorQO //高级搜索条件
                                       ){
        Integer poolCategory = clueQO.getPoolCategory();//0:个人池;1:私有池;2:分公司公有池;3:全国公有池)
        if(poolCategory != null){
            try{
                if(CluePoolNatureEnum.PRIVATE_POOL.getCluePoolNatureCode()== poolCategory ||//私有池
                        CluePoolNatureEnum.BRANCH_PUBLIC_POOL.getCluePoolNatureCode() == poolCategory ||//分公司公有池
                        CluePoolNatureEnum.NATIONAL_PUBLIC_POOL.getCluePoolNatureCode() == poolCategory){//全国公有池
                    DhPageInfo<ClueVO> clueVODhPageInfo = clueService.selectPublicPoolClueList(clueQO,clueSeniorQO,pageIndex,pageSize,sortName,sortOrder);
                    return new DhResponse(ResponseCodeEnum.OK.getResponseCode(),clueVODhPageInfo);
                }
                if(CluePoolNatureEnum.CLUE_POOL_CATEGORY_PERSONAL.getCluePoolNatureCode() == poolCategory){//个人池
                    DhPageInfo<ClueVO> clueVODhPageInfo = clueService.selectPrivatePoolClueList(clueQO,clueSeniorQO,pageIndex,pageSize,sortName,sortOrder);
                    return new DhResponse(ResponseCodeEnum.OK.getResponseCode(),clueVODhPageInfo);
                }
            }catch(Exception e){
                log.error("clue selectClueList error:", e);
                return new DhResponse(ResponseCodeEnum.SERVICE_ERROR.getResponseCode());
            }

        }
        return new DhResponse(ResponseCodeEnum.ERROR.getResponseCode());
    }

    /**
     * 线索--分配
     * @param distributeUserId   ---被分配人员ID
     * @param clueId             ---线索ID
     * @param poolId             ---线索池ID
     * @return
     */
    @PostMapping("/distributeClue")
    public DataResponse distributeClue(@RequestParam(value="distributeUserId",required = true)String distributeUserId,
                                       @RequestParam(value="clueId",required = true)String clueId,
                                       @RequestParam(value="poolId",required = true)String poolId
                                      ){
        try{
            Map<String,Object> result = clueService.updateClueDistribute(distributeUserId,clueId,poolId);
            if(result.containsKey("d000")){//分配成功
                return new DhResponse(ResponseCodeEnum.OK.getResponseCode(),result);
            }
            if(result.containsKey("d001")){//已分配的线索数达到最大值,不能进行分配
                return new DhResponse(ResponseCodeEnum.POOL_CAPACITY_EXCEEDED.getResponseCode(),result);
            }
            if(result.containsKey("d002")){//没有个人默认池不能分配
                return new DhResponse(ResponseCodeEnum.NO_DEFAULT_CLUE_POOL.getResponseCode(),result);
            }
            return new DhResponse(ResponseCodeEnum.OK.getResponseCode());
        }catch(Exception e){
            log.error("clue distributeClue error:", e);
            return new DhResponse(ResponseCodeEnum.SERVICE_ERROR.getResponseCode());
        }
    }

    /**
     * 线索--收回
     * @return
     */
    @PostMapping("/retrieveClue")
    public DataResponse retrieveClue(ClueQO clueQO){
        try{
            clueService.retrieveClue(clueQO);
            return new DhResponse(ResponseCodeEnum.OK.getResponseCode());
        }catch(Exception e){
            log.error("clue retrieveClue error:", e);
            return new DhResponse(ResponseCodeEnum.SERVICE_ERROR.getResponseCode());
        }
    }

    /**
     * 线索--删除
     * @param clueQO
     * @return
     */
    @PostMapping("/deleteClue")
    public DataResponse deleteClue(ClueQO clueQO){
        try{
            Boolean result = clueService.deleteClueById(clueQO);
            if(result){
                return new DhResponse(ResponseCodeEnum.OK.getResponseCode());
            }
        }catch(Exception e){
            log.error("clue deleteClue error:", e);
            return new DhResponse(ResponseCodeEnum.SERVICE_ERROR.getResponseCode());
        }
        return new DhResponse(ResponseCodeEnum.SERVICE_ERROR.getResponseCode());
    }

    /**
     * 线索--删除
     * @param clueQO
     * @return
     */
    @PostMapping("/batchDeleteClueByClueIds")
    public DataResponse batchDeleteClueByClueIds(String[] ids){
        try{
            if (null == ids || ids.length == 0) {
                return new DhResponse(ResponseCodeEnum.PARAMETER_ERROR.getResponseCode());
            }
            List<String> listIds = Arrays.asList(ids);
            Boolean result = clueService.batchDeleteClueByClueIds(listIds);
            if(result){
                return new DhResponse(ResponseCodeEnum.OK.getResponseCode());
            }
        }catch(Exception e){
            log.error("clue deleteClue error:", e);
            return new DhResponse(ResponseCodeEnum.SERVICE_ERROR.getResponseCode());
        }
        return new DhResponse(ResponseCodeEnum.SERVICE_ERROR.getResponseCode());
    }

    /**
     * 线索池删除时根据线索池ID查询该线索池里线索的已分配和已领取总数
     * @param cluePoolPublicId ---线索池ID
     * @return
     */
    @PostMapping("/selectDistributedOrReceiveCount")
    public DataResponse selectDistributedOrReceiveCount(@RequestParam(value="cluePoolPublicId",required = true) String cluePoolPublicId){
        try{
            if(clueService.selectDistributedOrReceiveCount(cluePoolPublicId) > 0){
                return new DhResponse(ResponseCodeEnum.EXIST_NO_RETRIEVE_CLUE.getResponseCode());
            }
        }catch(Exception e){
            log.error("clue selectDistributedOrReceiveCount error:", e);
            return new DhResponse(ResponseCodeEnum.SERVICE_ERROR.getResponseCode());
        }
        return new DhResponse(ResponseCodeEnum.ERROR.getResponseCode());
    }

    /**
     * 根据线索池ID查询公司(分公司公有池)
     * @param cluePollId  ---线索池ID
     * @return
     */
    @GetMapping("/selectBranchCompany")
    public DataResponse selectBranchCompany(@RequestParam(value="cluePollId",required = true) String cluePollId){
        try{
            List<UserCompanyVO>  userCompanyVOList = clueService.selectDistributeCompany(cluePollId);
            return new DhResponse(ResponseCodeEnum.OK.getResponseCode(),userCompanyVOList);
        }catch(Exception e){
            log.error("clue selectBranchCompany error:", e);
            return new DhResponse(ResponseCodeEnum.SERVICE_ERROR.getResponseCode());
        }
    }

    /**
     * 根据线用户名查询用户信息及公司信息(全国的)
     * @param userName  ---用户名
     * @return
     */
    @GetMapping("/selectUserAndCompanyByName")
    public DataResponse selectUserAndCompanyByName(@RequestParam(value="userName",required = true) String userName){
        try{
            List<UserCompanyVO> userCompanyVO = clueService.selectUserAndCompany(userName);
            return new DhResponse(ResponseCodeEnum.OK.getResponseCode(),userCompanyVO);
        }catch(Exception e){
            log.error("clue selectUserAndCompanyByName error:", e);
            return new DhResponse(ResponseCodeEnum.SERVICE_ERROR.getResponseCode());
        }
    }

    /**
     * 根据线索池
     * @param cluePollId  ---线索池ID
     * @return
     */
    @GetMapping("/selectUserByPoolPermission")
    public DataResponse selectUserByPoolPermission(@RequestParam(value="cluePollId",required = true) String cluePollId,
                                                   @RequestParam(value="userName",required = false) String userName
    ){
        try{
            List<UserCompanyVO> userCompanyVOList = clueService.selectDistributeCompany(cluePollId);
            if(userCompanyVOList != null && userCompanyVOList.size() > 0){
                List<String> companyIds = userCompanyVOList.stream().map(company -> company.getCompanyId()).collect(Collectors.toList());
                return new DhResponse(ResponseCodeEnum.OK.getResponseCode(),clueService.selectUserByPoolPermission(companyIds,userName));
            }
            return new DhResponse(ResponseCodeEnum.ERROR.getResponseCode());
        }catch(Exception e){
            log.error("clue selectUserByPoolPermission error:", e);
            return new DhResponse(ResponseCodeEnum.SERVICE_ERROR.getResponseCode());
        }
    }

    /**
     * 线索池详情-线索清单-领取记录
     * @param request
     * @param pageIndex
     * @param pageSize
     * @param clueId
     * @return
     */
    @PostMapping("/selectClueReceiveList")
    public DataResponse selectClueReceiveList(HttpServletRequest request,//request
                                             @RequestParam(value = "pageIndex", required = true) Integer pageIndex,//页码
                                             @RequestParam(value = "pageSize", required = true) Integer pageSize,//分页大小
                                             @RequestParam(value="clueId",required = false) String clueId){//线索ID
        DhPageInfo<ClueReceiveVO> clueReceiveVO = clueReceiveService.selectClueReceiveVOList(pageIndex,pageSize,clueId);
        return new DhResponse(ResponseCodeEnum.OK.getResponseCode(),clueReceiveVO);
    }

    /**
     * 线索池详情-线索清单-退回记录
     * @param request
     * @param pageIndex
     * @param pageSize
     * @param clueId
     * @return
     */
    @PostMapping("/selectClueReturnList")
    public DataResponse selectClueReturnList(HttpServletRequest request,//request
                                             @RequestParam(value = "pageIndex", required = true) Integer pageIndex,//页码
                                             @RequestParam(value = "pageSize", required = true) Integer pageSize,//分页大小
                                             @RequestParam(value="clueId",required = false) String clueId){//线索ID
        DhPageInfo<ClueReturnVO> clueReturnVO =  clueReturnService.selectClueReturnVOList(pageIndex,pageSize,clueId);
        return new DhResponse(ResponseCodeEnum.OK.getResponseCode(),clueReturnVO);
    }

    /**
     * 线索池详情-线索清单-跟进记录
     * @param request
     * @param pageIndex
     * @param pageSize
     * @param clueId
     * @return
     */
    @PostMapping("/selectClueFollowList")
    public DataResponse selectClueFollowList(HttpServletRequest request,//request
                                                  @RequestParam(value = "pageIndex", required = true) Integer pageIndex,//页码
                                                  @RequestParam(value = "pageSize", required = true) Integer pageSize,//分页大小
                                                  @RequestParam(value="clueId",required = false) String clueId){//线索ID
        DhPageInfo<ClueFollowVO> clueFollowVO =  clueFollowService.selectClueFollowVOList(pageIndex,pageSize,clueId);
        return new DhResponse(ResponseCodeEnum.OK.getResponseCode(),clueFollowVO);
    }

    /**
     * 线索池详情-线索清单-拜访记录
     * @param request
     * @param pageIndex
     * @param pageSize
     * @param clueId
     * @return
     */
    @PostMapping("/selectClueVisitList")
    public DataResponse selectClueVisitList(HttpServletRequest request,//request
                                             @RequestParam(value = "pageIndex", required = true) Integer pageIndex,//页码
                                             @RequestParam(value = "pageSize", required = true) Integer pageSize,//分页大小
                                             @RequestParam(value="clueId",required = false) String clueId){//线索ID
        DhPageInfo<ClueVisitRecordVO> clueVisitRecords = clueVisitRecordService.selectClueVisitRecords(pageIndex,pageSize,clueId);
        return new DhResponse(ResponseCodeEnum.OK.getResponseCode(),clueVisitRecords);
    }

    /**
     * 线索池详情-线索清单-联系人记录
     * @param request
     * @param pageIndex
     * @param pageSize
     * @param clueId
     * @return
     */
    @PostMapping("/selectContactsList")
    public DataResponse selectContactsList(HttpServletRequest request,//request
                                            @RequestParam(value = "pageIndex", required = true) Integer pageIndex,//页码
                                            @RequestParam(value = "pageSize", required = true) Integer pageSize,//分页大小
                                            @RequestParam(value="clueId",required = false) String clueId){//线索ID
        DhPageInfo<ClueContactVO> clueContactVOs = clueContactService.selectClueContactVOs(pageIndex,pageSize,clueId);
        return new DhResponse(ResponseCodeEnum.OK.getResponseCode(),clueContactVOs);
    }


    /**
     * 编辑线索
     * @param clue
     * @return
     */
    @PostMapping("/editClue")
    public DataResponse editClue(HttpServletRequest request,
                                @RequestBody Clue clue) {
        try {
            int result = clueService.editClue(clue);
            if (result == 0) {
                return new DhResponse(ResponseCodeEnum.OK.getResponseCode());
            } else if(result == 2){
                return new DhResponse(ResponseCodeEnum.CLUE_NAME_DUPLICATE.getResponseCode());
            }
            return new DhResponse(ResponseCodeEnum.ERROR.getResponseCode());
        }catch(Exception e){
            log.error("clue editClue error:", e);
            return new DhResponse(ResponseCodeEnum.SERVICE_ERROR.getResponseCode());
        }
    }

    /**
     * 修改标签
     * @return
     */
    @PostMapping("/updateUserClueTag")
    public DataResponse updateUserClueTag(@RequestBody JSONObject jsonObject) {
        try {
            int result = clueService.updateUserClueTag(jsonObject.getString("tag"), jsonObject.getString("clueId"));
            if (result > 0) {
                return new DhResponse(ResponseCodeEnum.OK.getResponseCode());
            }
            return new DhResponse(ResponseCodeEnum.ERROR.getResponseCode());
        }catch(Exception e){
            log.error("clue updateUserClueTag error:", e);
            return new DhResponse(ResponseCodeEnum.SERVICE_ERROR.getResponseCode());
        }
    }

    /**
     *info 用户模块-线索池公海-线索清单
     * @return
     */
    @PostMapping("/pageList")
    public DataResponse pageList(@RequestParam(value = "pageIndex", required = true) Integer pageIndex,//页码
                                       @RequestParam(value = "pageSize", required = true) Integer pageSize,//分页大小
                                       @RequestParam(value="sortName",required = false) String sortName,//排序列名字
                                       @RequestParam(value="sortOrder",required = false) String sortOrder,//排序规则(asc/desc)
                                       ClueQO clueQO){//查询条件
        try{
            DhPageInfo<ClueVO> clueVODhPageInfo = clueService.selectClueInfo(clueQO,pageIndex,pageSize,sortName,sortOrder);
            return new DhResponse(ResponseCodeEnum.OK.getResponseCode(),clueVODhPageInfo);
        }catch(Exception e){
            log.error("clue pageList error:", e);
            return new DhResponse(ResponseCodeEnum.ERROR.getResponseCode());
        }
    }

    /**
     *info 用户模块-我的线索池-线索清单
     * @return
     */
    @PostMapping("/getMyClueList")
    public DataResponse getMyClueList(@RequestParam(value = "pageIndex", required = true) Integer pageIndex,//页码
                                      @RequestParam(value = "pageSize", required = true) Integer pageSize,//分页大小
                                      @RequestParam(value="sortName",required = false) String sortName,//排序列名字
                                      @RequestParam(value="sortOrder",required = false) String sortOrder,//排序规则(asc/desc)
                                      ClueQO clueQO, ClueExtentQO clueExtentQO){//查询条件
        try{
            DhPageInfo<ClueVO> clueVODhPageInfo = clueService.getMyClueList(clueQO, clueExtentQO, pageIndex,pageSize,sortName,sortOrder);
            return new DhResponse(ResponseCodeEnum.OK.getResponseCode(),clueVODhPageInfo);
        }catch(Exception e){
            log.error("clue getMyClueList error:", e);
            return new DhResponse(ResponseCodeEnum.ERROR.getResponseCode());
        }
    }

    public static void main(String[] args) {
        System.out.println(CommonUtils.getGUID());
    }



    /**
     * @author wll
     * info 我的线索池-线索清单释放
     * @param clueQO
     * @return
     */
    @PostMapping("/releaseClue")
    public DataResponse releaseClue(ClueQO clueQO){
        try{
            clueService.releaseClue(clueQO);
            return new DhResponse(ResponseCodeEnum.OK.getResponseCode());
        }catch(Exception e){
            log.error("clue releaseClue error:", e);
            return new DhResponse(ResponseCodeEnum.SERVICE_ERROR.getResponseCode());
        }
    }


    /**
     * @author wll
     * info 线索池公海-线索表单-领取
     * @param clueQO
     * @return
     */
    @PostMapping("/receiveClue")
    public DataResponse receiveClue(ClueQO clueQO,@RequestParam(value="poolId") String poolId){
        try{
            JSONObject info = clueService.receiveClue(clueQO,poolId);
            return new DhResponse(ResponseCodeEnum.OK.getResponseCode(),info);
        }catch(Exception e){
            log.error("clue receiveClue error:", e);
            return new DhResponse(ResponseCodeEnum.SERVICE_ERROR.getResponseCode());
        }
    }


    /**
     * @author wll
     * info 用户模块-线索清单-查看-线索记录
     * @param clueQO
     * @param tabType  1跟进记录 2拜访记录 4新增联系人
     * @return
     */
    @PostMapping("/userClueRecord")
    public DataResponse userClueRecord(@RequestParam(value = "pageIndex") Integer pageIndex,
                                       @RequestParam(value = "pageSize") Integer pageSize,
                                       @RequestParam(value = "sort", required = false) String sort,
                                       @RequestParam(value = "sortOrder", required = false) String sortOrder,
            ClueQO clueQO,@RequestParam(value="tabType") String tabType){
        if(tabType.equals("1")){//跟进记录
            DhPageInfo<ClueFollowVO> clueFollows = clueFollowService.selectClueFollowVOList(pageIndex,pageSize,clueQO.getClueId());
            return new DhResponse(ResponseCodeEnum.OK.getResponseCode(), clueFollows);
        }else if(tabType.equals("2")){//拜访记录
             DhPageInfo<ClueVisitRecordVO> clueVisitRecords = clueVisitRecordService.selectClueVisitRecords(pageIndex,pageSize,clueQO.getClueId());
             return new DhResponse(ResponseCodeEnum.OK.getResponseCode(), clueVisitRecords);
        }else{//联系人记录
            DhPageInfo<ClueContactVO> clueContactVOs = clueContactService.selectClueContactVOs(pageIndex,pageSize,clueQO.getClueId());
            return new DhResponse(ResponseCodeEnum.OK.getResponseCode(), clueContactVOs);
        }
    }
}
